package com.baozhun.mall.common.widget.customview.addresspicker

import android.content.Context
import android.view.View
import com.baozhun.mall.common.R
import com.baozhun.mall.common.databinding.WidgetAddressPickerLayoutBinding
import com.baozhun.mall.common.ext.dp
import com.baozhun.mall.common.ext.showToast
import com.baozhun.mall.common.listener.ViewOnClickListener
import com.baozhun.mall.common.model.bean.AddressInfo
import com.baozhun.mall.common.model.bean.HotRegionBean
import com.baozhun.mall.common.model.bean.RegionBean
import com.baozhun.mall.common.widget.dialog.BaseBottomPopupView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.fondesa.recyclerviewdivider.dividerBuilder

/**
 * @Title：
 * @Description：
 * @Author：xing.luo
 * @Since：2022/11/12
 * @Version：1.0.0
 */
class AddressPickerDialog(context: Context, val addressInfo: AddressInfo?,
                          val hotRegion: MutableList<HotRegionBean>,
                          val region: MutableList<RegionBean>,
                          val listener: OnRegionPicked
    ) :
    BaseBottomPopupView<WidgetAddressPickerLayoutBinding>(context),
    ViewOnClickListener {
    var current = 1
    var first = true
    companion object{
        var currentAddress: AddressInfo? = null
    }

    override fun getImplLayoutId(): Int {
        return R.layout.widget_address_picker_layout
    }

    override fun onCreate() {
        super.onCreate()
        initView()
        initData()
    }

    private fun initView() {


    }

    fun initData() {
        currentAddress = addressInfo
        if (currentAddress == null || currentAddress?.getDetailAddress().isNullOrEmpty()) {
            currentAddress = AddressInfo(0, "", "", "", "", "", "", "", "", "", "", "", 0)
            initProvince()
        } else {
            current = 4
            mBinding.pickerProvince.text = currentAddress?.province
            mBinding.pickerCity.text = currentAddress?.city
            mBinding.pickerArea.text = currentAddress?.county
            mBinding.pickerDistrict.text = currentAddress?.street
            initStreet()
        }

    }

    override fun onClick(v: View?) {
        when(v?.id) {
            R.id.iv_close -> dismiss()
            R.id.done -> {
                if (currentAddress == null || current < 4) {
                    context.showToast("请选择完整区域信息")
                } else {
                    listener.onPick(currentAddress!!)
                    dismiss()
                }
            }
            R.id.picker_province -> {
                initProvince()
            }
            R.id.picker_city -> {
                if(currentAddress?.city_id?.isNotEmpty() == true) {
                    initCity()
                }
            }
            R.id.picker_area -> {
                if (currentAddress?.street_id?.isNotEmpty() == true) {
                    initArea()
                }
            }
            R.id.picker_district -> {

            }
        }

    }

    private fun initProvince() {
        resetState()
        current = 1
        mBinding.pickerProvince.setTextColor(resources.getColor(com.baozhun.mall.res.R.color.main_color))
        mBinding.titlePickerContent.text = resources.getString(com.baozhun.mall.res.R.string.picker_province)
        mBinding.usefulLayout.visibility = View.VISIBLE
        val hotAdapter = UsefulCityAdapter(hotRegion)
        mBinding.usefulCityRv.adapter = hotAdapter
        if (first) {
            mBinding.usefulCityRv.addItemDecoration(context.dividerBuilder().asSpace().size(5.dp).build())
            first = false
        }
        hotAdapter.setOnItemClickListener(object : OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                val hotRegion = hotRegion[position]
                if (hotRegion.city != currentAddress?.city) {
                    resetArea()
                    resetDistrict()
                }
                mBinding.pickerProvince.text = hotRegion.province
                mBinding.pickerCity.text = hotRegion.city
                currentAddress?.province = hotRegion.province
                currentAddress?.province_id = hotRegion.province_id
                currentAddress?.city = hotRegion.city
                currentAddress?.city_id = hotRegion.city_id
                initArea()
            }
        })

        val adapter = CommonPickerAdapter(sort(region))
        mBinding.pickerContentRv.adapter = adapter
        adapter.setOnItemClickListener(object : OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                val region = adapter.getItem(position) as RegionBean
                mBinding.pickerProvince.text = region.name
                if (region.name != currentAddress?.province) {
                    resetCity()
                    resetArea()
                    resetDistrict()
                }
                currentAddress?.province = region.name
                currentAddress?.province_id = region.id
                initCity()
            }
        })
    }

    private fun initCity() {
        resetState()
        current = 2
        mBinding.pickerCity.setTextColor(resources.getColor(com.baozhun.mall.res.R.color.main_color))
        mBinding.titlePickerContent.text = resources.getString(com.baozhun.mall.res.R.string.picker_city)

        val adapter = CommonPickerAdapter(sort(getRegionById(currentAddress?.province_id!!)?.child!!))
        mBinding.pickerContentRv.adapter = adapter
        adapter.setOnItemClickListener(object : OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                val region = adapter.getItem(position) as RegionBean
                mBinding.pickerCity.text = region.name
                if (region.name != currentAddress?.city) {
                    resetArea()
                    resetDistrict()
                }
                currentAddress?.city = region.name
                currentAddress?.city_id = region.id
                initArea()
            }
        })
    }

    private fun initArea() {
        resetState()
        current = 3
        mBinding.pickerArea.setTextColor(resources.getColor(com.baozhun.mall.res.R.color.main_color))
        mBinding.titlePickerContent.text = resources.getString(com.baozhun.mall.res.R.string.picker_area)

        val adapter = CommonPickerAdapter(sort(getRegionById(currentAddress?.city_id!!)?.child!!))
        mBinding.pickerContentRv.adapter = adapter
        adapter.setOnItemClickListener(object : OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                val region = adapter.getItem(position) as RegionBean
                mBinding.pickerArea.text = region.name
                if (region.name != currentAddress?.county) {
                    resetDistrict()
                }
                currentAddress?.county = region.name
                currentAddress?.county_id = region.id
                initStreet()
            }
        })
    }

    private fun initStreet() {
        resetState()
        current = 4
        mBinding.pickerDistrict.setTextColor(resources.getColor(com.baozhun.mall.res.R.color.main_color))
        mBinding.titlePickerContent.text = resources.getString(com.baozhun.mall.res.R.string.picker_district)

        val adapter = CommonPickerAdapter(sort(getRegionById(currentAddress?.county_id!!)?.child!!))
        mBinding.pickerContentRv.adapter = adapter
        adapter.setOnItemClickListener(object : OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                val region = adapter.getItem(position) as RegionBean
                mBinding.pickerDistrict.text = region.name
                currentAddress?.street = region.name
                currentAddress?.street_id = region.id
                adapter.notifyDataSetChanged()
            }
        })
    }

    private fun resetState() {
        mBinding.pickerProvince.setTextColor(resources.getColor(com.baozhun.mall.res.R.color.color_333333))
        mBinding.pickerCity.setTextColor(resources.getColor(com.baozhun.mall.res.R.color.color_333333))
        mBinding.pickerArea.setTextColor(resources.getColor(com.baozhun.mall.res.R.color.color_333333))
        mBinding.pickerDistrict.setTextColor(resources.getColor(com.baozhun.mall.res.R.color.color_333333))
        mBinding.usefulLayout.visibility = View.GONE
    }

    private fun resetCity() {
        currentAddress?.city = ""
        currentAddress?.city_id = ""
        mBinding.pickerCity.text = resources.getString(com.baozhun.mall.res.R.string.address_picker_city)
    }

    private fun resetArea() {
        currentAddress?.county = ""
        currentAddress?.county_id = ""
        mBinding.pickerArea.text = resources.getString(com.baozhun.mall.res.R.string.address_picker_area)
    }

    private fun resetDistrict() {
        currentAddress?.street = ""
        currentAddress?.street_id = ""
        mBinding.pickerDistrict.text = resources.getString(com.baozhun.mall.res.R.string.address_picker_district)
    }

    private fun getRegionById(id: String): RegionBean?{
        for (province in region) {
            if (id == province.id) {
                return province
            }
            for (city in province.child) {
                if (id == city.id) {
                    return city
                }
                for (area in city.child) {
                    if (id == area.id) {
                        return area
                    }
                }
            }
        }
        return null
    }

    private fun sort(data: MutableList<RegionBean>): MutableList<RegionBean> {
        data.sortBy {
            it -> it.pinyin_prefix
        }
        var prefix = ""
        for (item in data) {
            if (item.pinyin_prefix != prefix) {
                item.isShow = true
                prefix = item.pinyin_prefix
            }
        }

        return data
    }

}